package com.leetcode;

import java.util.Scanner;

public class No42 {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        String []temp = str.split(",");
        int len = temp.length;
        int[] array = new int[len];
        for(int i = 0;i < len;i++){
            array[i] = Integer.parseInt(temp[i]);
        }
        int rainWater = rainWater(array);
        System.out.println(rainWater);
        sc.close();
    }

    private static int rainWater(int [] array){
        if(array == null || array.length < 3){
            return 0;
        }
        int len = array.length;

        int leftMaxHeightIdx = 0;
        int rightMaxHeightIdx = len - 1;
        int max = 0;
        // 寻找最大值
        for(int i = 0;i < len;i++){
            if(max < array[i]){
                max = array[i];
            }
        }
        // 找到左边界
        for(int i = 0;i < len;i++){
            if(max == array[i]){
                leftMaxHeightIdx = i;
                break;
            }
        }
        // 找到右边界
        for(int j = len - 1;j >= 0;j--){
            if(max == array[j]){
                rightMaxHeightIdx = j;
                break;
            }
        }

        // 左边的柱子计算
        int left = 0;
        int r = 0;
        int maxWater = 0;

        while(left + 2 <= leftMaxHeightIdx){
            // 跳过柱子为0的情况
            while(array[left] == 0){
                left++;
            }
            r = left + 1;
            while(r <= leftMaxHeightIdx && array[left] > array[r]){
                r++;
            }
            if(r > leftMaxHeightIdx ){
                left++;
            }else{
                int leftHeight = array[left];
                for(int i = left ;i < r;i++){
                    maxWater += (leftHeight - array[i]);
                }
                left = r;
            }
        }

        // 右边的柱子计算
        int right = len - 1;
        int l = len - 1;
        while(right - 2 >= rightMaxHeightIdx){
            while(array[right] == 0){
                right--;
            }
            l = right - 1;
            while(l >= rightMaxHeightIdx && array[l] < array[right]){
                l--;
            }
            if(l < rightMaxHeightIdx){
                break;
            }else{
                int rightHeight = array[right];
                for(int j = right ; j > l;j--){
                    maxWater = maxWater + (rightHeight - array[j]);
                }
                right = l;
            }
        }

        // （若有）中间的柱子计算
        if((rightMaxHeightIdx - leftMaxHeightIdx) <= 1){
            maxWater += 0;
        }else{
            for(int i = leftMaxHeightIdx + 1;i < rightMaxHeightIdx;i++){
                maxWater += (max - array[i]);
            }
        }
        return maxWater;
    }
}
